import { Component, Vue } from 'vue-property-decorator';
import style from '@/styles/views/user.module.less';
import viewsStyle from '@/styles/views/views.module.less';
import { EapLayout } from '@/components';
import { Button, Dialog, Field, Icon, NavBar, Overlay, SwipeCell } from 'vant';
import { IUser } from '@/interfaces/auth.interface';
import defaultAvatar from '@/assets/edger.png';
import _ from 'lodash';
import { IResponse } from '@/interfaces/common.interface';
import { IManager } from '@/interfaces/store.interface';

Vue.use(Dialog);

@Component({
  components: {
    'eap-layout': EapLayout,
    'van-overlay': Overlay,
    'van-nav-bar': NavBar,
    'van-button': Button,
    'van-icon': Icon,
    'van-field': Field,
    'van-swipe-cell': SwipeCell
  }
})
export default class User extends Vue {
  private showBigAvatar = false;
  private showModel = false;
  private formData = {
    nickname: '',
    profile: '',
    acoid: ''
  };
  private showAcoidError = false;
  private showNameError = false;

  private get accountInfo(): IUser {
    return this.$store.state.accountInfo || {};
  }

  private get managers(): IUser[] {
    return this.$store.state.managers || [];
  }

  private get isSuperManager(): boolean {
    const { managers, accountInfo } = this.$store.state;
    if (accountInfo.acoid) {
      return _.find(managers, { acoid: accountInfo.acoid, super: true });
    }
    return false;
  }

  public render() {
    return (
      <eap-layout>
        <van-nav-bar title='用户管理' slot='header' />
        <div class={style['user']}>
          <div class={style['user-self']}>
            <img
              src={this.accountInfo.profile || defaultAvatar}
              alt='avatar'
              on-click={() => {
                this.showBigAvatar = true;
              }}
            />
            <p>{`欢迎您！ ${this.accountInfo.nickname || '***'}【${this.accountInfo.acoid || '-'}】`}</p>
          </div>
          <div class={style['user-manager']}>
            <div class={style['user-manager-title']}>
              <h3>管理员列表</h3>
              {this.isSuperManager && (
                <van-button
                  color='#20a5df'
                  size='small'
                  class={viewsStyle['touch']}
                  on-click={() => {
                    this.showAddModel();
                  }}>
                  添加
                </van-button>
              )}
            </div>

            <div class={style['user-manager-list']}>
              {this.managers.map((item: IManager) => (
                <van-swipe-cell>
                  <div class={style['user-manager-item']}>
                    <img src={defaultAvatar} alt='avatar' />
                    <span>
                      {item.nickname || '***'}
                      {item.super && `【超管】`}
                    </span>
                  </div>
                  {this.accountInfo.acoid !== item.acoid && (
                    <template slot='right'>
                      <van-button type='danger' icon='delete-o' on-click={() => this.deleteManager(item.acoid)} />
                    </template>
                  )}
                </van-swipe-cell>
              ))}
            </div>
          </div>
        </div>
        <van-overlay show={this.showBigAvatar} on-click={() => (this.showBigAvatar = false)}>
          <img src={this.accountInfo.profile || defaultAvatar} alt='avatar' class={style['user-big-avatar']} />
        </van-overlay>
        {this.renderAddModel()}
      </eap-layout>
    );
  }

  private renderAddModel() {
    return (
      <van-dialog
        v-model={this.showModel}
        title='管理员信息录入'
        showConfirmButton={false}
        closeOnClickOverlay
        class={viewsStyle['model']}>
        {this.renderDeviceSetting()}
      </van-dialog>
    );
  }

  private renderDeviceSetting() {
    return (
      <div class={viewsStyle['model-settings']}>
        <h5>授权acoid：</h5>
        <van-field
          v-model={this.formData.acoid}
          placeholder='请输入授权acoid'
          error-message={this.showAcoidError ? '授权acoid不可为空！' : ''}
        />
        <h5>用户名：</h5>
        <van-field
          v-model={this.formData.nickname}
          placeholder='请输入用户名'
          error-message={this.showNameError ? '用户名不可为空！' : ''}
        />
        <div class={viewsStyle['model-btns']}>
          <van-button
            type='default'
            size='small'
            class={viewsStyle['touch']}
            on-click={() => {
              this.showModel = false;
            }}>
            取消
          </van-button>
          <van-button
            color='#20a5df'
            size='small'
            class={this.formData.acoid.trim() && this.formData.nickname.trim() && viewsStyle['touch']}
            disabled={!this.formData.acoid.trim() || !this.formData.nickname.trim()}
            on-click={this.submitForm}>
            确定
          </van-button>
        </div>
      </div>
    );
  }

  private showAddModel() {
    this.showAcoidError = false;
    this.showNameError = false;
    this.formData = { nickname: '', acoid: '', profile: '' };
    this.showModel = true;
  }

  private submitForm() {
    this.showAcoidError = this.formData.acoid.trim() === '';
    this.showNameError = this.formData.nickname.trim() === '';
    if (!this.showAcoidError && !this.showNameError) {
      this.$socket.client.emit('add-manager', this.formData, (data: IResponse) => {
        if (!data.result) {
          this.$message.error(data.message);
        }
      });
      this.showModel = false;
    }
  }

  private deleteManager(acoid: string) {
    if (this.isSuperManager) {
      this.$socket.client.emit('delete-manager', acoid, (data: IResponse) => {
        if (!data.result) {
          this.$message.error(data.message);
        }
      });
    }
  }
}
